<?php

namespace app\api\controller;

use think\App;
use think\Controller;
use think\Db;
use think\Request;
use app\api\model\Brandm;
use think\facade\Config;

class Brand extends Controller
{
    //获取品牌分页列表
    public function page(Request $request)
    {
        // 获取参数
        $page = $request->param('page', 1); // 当前页
        $rows = $request->param('rows', 10); // 每页记录数
        $search = $request->param('search', ''); // 搜索条件
        $sortBy = $request->param('sortBy', 'id'); // 排序字段
        $sortDesc = $request->param('sortDesc', 'ASC'); // 是否倒序
        $sortDesc = $sortDesc == 'true' ? 'DESC' : 'ASC';
        // 查询数据库
        // 1、每页数据
        $itemList = Brandm::whereLike('initial', "%{$search}%")
            ->order($sortBy, $sortDesc)
            ->page($page, $rows)
            ->select();
        // 2、总记录数
        $total = count(Brandm::whereLike('initial', "%{$search}%")->select());
        // 3、总页数
        $totalPage = ceil($total / $rows);
        $data = [
            'total' => $total,
            'items' => $itemList,
            'totalPage' => $totalPage
        ];
        return json($data);
    }

    // 新增品牌
    public function addBrand(Request $request)
    {
        // 1、解析请求数据
        // 2、向品牌表添加品牌，并接收返回的品牌ID
        $brand = Brandm::create($request->param());
        // 3、向分类品牌第三方表添加数据
        $cids = $request->param('cids');
        foreach (explode(',', $cids) as $cid) {
            $data = ['category_id' => $cid, 'brand_id' => $brand->id];
            Db::table('tb_category_brand')->insert($data);
        }

        // 4、响应数据
        return json($brand, 201);
//        return  json($request->param(), 201);
    }

    // 根据品牌路由查找分类信息
    public function findCategoriesByBid(Request $request, $bid)
    {
//        // 1、解析请求参数品牌ID
//        $bid = $request->param('bid');
        if (empty($bid)) {
            return json('请求品牌不能为空', 404);
        }
        // 2、根据品牌ID查询分类品牌表，获取分类信息
//        $cids = DB::table('tb_category_brand')
//                    ->field('category_id')
//                    ->where('brand_id', $bid)
//                    ->select();
//        foreach ($cids as $key => $value) {
////            echo $key.'----'.$value['category_id'].'<br />';
//            $cids[$key]['value'] = $value['category_id'];
//        }
////        echo dump($cids);
        $brand = Brandm::get($bid);
        $categories = $brand->categories;
//        echo dump($categories);
        $cids = array();
        foreach ($categories as $index => $cate) {
            $cids[$index]['id'] = $cate->id;
            $cids[$index]['name'] = $cate->name;
        }
        // 3、响应请求
        return json($cids, 200);
    }

    // 图片上传
    public function uploadImage(Request $request)
    {
        // 1、获取上传文件对象
        $file = $request->file('file');
        // 2、移动上传文件到网站根目录下的uploads文件夹
        $info = $file->move('./uploads');
        if ($info) { // 判断文件是否移动成功
            // 返回文件路径
            $filePath = Config::get('file_storage_path') . $info->getSaveName();
            return str_replace('\\', '/', $filePath);
        } else {
            return $file->getError();
        }
    }

    // 修改品牌
    public function editBrand(Request $request)
    {
        $newBrand = $request->param('brand');
        if (!$newBrand) {
            return json('数据不能为空', 404);
        }

        $brand = Brandm::update($newBrand);
        $newCat = $request->param('categories');
        // 根据分类关联更新中间表
        $originCat = Db::table('tb_category_brand')
            ->where('brand_id', $brand->id)
            ->column('category_id');

        $insert = array_diff($newCat, $originCat);
        $delete = array_diff($originCat, $newCat);

        if ($insert) {
            $brand->categories()->saveAll($insert);
        }
        if ($delete) {
            $brand->categories()->detach($delete);
        }

        $last = Db::table('tb_category_brand')
            ->where('brand_id', $brand->id)
            ->select();
       return json('修改完成', 200);
    }
}
